/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pocketsweet.chat.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMCallStateChangeListener;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EMServiceNotReadyException;
import com.pocketsweet.R;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.model.MLDate;
import com.pocketsweet.model.MLLovers;
import com.pocketsweet.model.MLReportRecord;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Identification;
import com.pocketsweet.ui.uilib.ActionSheetDialog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.Rotate3dAnimation;
import com.pocketsweet.ui.uilib.coutdownView;
import com.pocketsweet.ui.uilib.ActionSheetDialog.OnSheetItemClickListener;
import com.pocketsweet.ui.uilib.ActionSheetDialog.SheetItemColor;
import com.pocketsweet.ui.uilib.coutdownView.OnTimeCompleteListener;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * 语音通话页面
 *
 */
public class RandomCallActivity extends CallActivity implements OnClickListener {
    private ImageView ivChange;
    private ImageView ivLike;
    private ImageView swing_card;
    private ImageView handsFreeImage;

    private MLReportRecord mlReportRecord;

    private boolean isMuteState;
    private boolean isHandsfreeState;

    private TextView callStateTextView;
    private int streamID;
    private boolean endCallTriggerByMe = false;
    private Handler handler = new Handler();
    private TextView nickTextView;
    private TextView durationTextView;
    private Chronometer chronometer;
    String st1;
    private boolean isAnswered;
    private RelativeLayout voiceContronlLayout;

    private LinearLayout topLayout;
    private LinearLayout llHeaderContent;
    private LinearLayout llCountDown;

    // 头部
    private ImageView ibClose;
    private TextView tvWaiting;
    private TextView tvReport;
    // 人物信息
    private LinearLayout llUserContent;
    private TextView tvCity;
    private TextView tvXingzuo;
    private TextView tvType;
    private TextView tvWillingCall;
    private LinearLayout llWillingCall;

    private LinearLayout llUserTip;

    private int countdownTime = 180;
    private coutdownView countdownTimer;
    public boolean isBeLiked = false;
    private boolean liked = false;

    public static RandomCallActivity randomCallInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            finish();
            return;
        }
        randomCallInstance = this;
        setContentView(R.layout.activity_random_call);
        ivChange = (ImageView) findViewById(R.id.ivChange);

        swing_card = (ImageView) findViewById(R.id.swing_card);
        ivLike = (ImageView) findViewById(R.id.ivLike);
        handsFreeImage = (ImageView) findViewById(R.id.iv_handsfree);
        callStateTextView = (TextView) findViewById(R.id.tv_call_state);
        nickTextView = (TextView) findViewById(R.id.tv_nick);
        durationTextView = (TextView) findViewById(R.id.tv_calling_duration);
        chronometer = (Chronometer) findViewById(R.id.chronometer);
        voiceContronlLayout = (RelativeLayout) findViewById(R.id.ll_voice_control);
        countdownTimer = (coutdownView) findViewById(R.id.countdownTimer);
        topLayout = (LinearLayout) findViewById(R.id.topLayout);
        llHeaderContent = (LinearLayout) findViewById(R.id.llHeaderContent);
        llCountDown = (LinearLayout) findViewById(R.id.llCountDown);
        ibClose = (ImageView) findViewById(R.id.ibClose);
        tvWaiting = (TextView) findViewById(R.id.tvWaiting);
        tvReport = (TextView) findViewById(R.id.tvReport);
        // 人物信息
        tvCity = (TextView) findViewById(R.id.tvCity);
        tvXingzuo = (TextView) findViewById(R.id.tvXingzuo);
        tvType = (TextView) findViewById(R.id.tvType);
        tvWillingCall = (TextView) findViewById(R.id.tvWillingCall);
        llWillingCall = (LinearLayout) findViewById(R.id.llWillingCall);
        llUserContent = (LinearLayout) findViewById(R.id.llUserContent);
        llUserTip = (LinearLayout) findViewById(R.id.llUserTip);

        ivChange.setOnClickListener(this);
        ibClose.setOnClickListener(this);
        tvReport.setOnClickListener(this);
        ivLike.setOnClickListener(this);
        handsFreeImage.setOnClickListener(this);

        // 跳动动画
        llUserTip.setAnimation(AnimationUtils.loadAnimation(
                MLApplication.getContext(), R.anim.downup));
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        // 注册语音电话的状态的监听
        addCallStateListener();
        msgid = UUID.randomUUID().toString();

        username = getIntent().getStringExtra("username");
        nickname = getIntent().getStringExtra("nickname");
        avatar = getIntent().getStringExtra("avatar");
        curDateID = getIntent().getStringExtra("curDateID");
        charge = getIntent().getDoubleExtra("charge", 0);
        curUser = UserService.getCurrentUser();
        balance = curUser.getBalance();

        // 加载人物信息
        AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
        query.getInBackground(username, new GetCallback<MLUser>() {

            @Override
            public void done(MLUser user, AVException e) {
                if (e == null) {
                    llUserContent.setVisibility(View.VISIBLE);
                    tvCity.setText(user.getLocationCity());
                    tvXingzuo.setText(user.getConstellation());
                    tvType.setText(user.getBelong());
                    if (user.getWillingTags() != null
                            && user.getWillingTags().size() != 0) {
                        llWillingCall.setVisibility(View.VISIBLE);
                        tvWillingCall.setText(user.getWillingTags().get(0));
                    }
                }
            }
        });

        if (!StringUtils.isEmpty(avatar)) {
            UserService.displayAvatar(avatar, swing_card);
        }
        // 语音电话是否为接收的
        isInComingCall = getIntent().getBooleanExtra("isComingCall", false);

        // 设置通话人
        nickTextView.setText(nickname);
        if (!isInComingCall) {// 拨打电话
            soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
            outgoing = soundPool.load(this, R.raw.outgoing, 1);
            st1 = getResources()
                    .getString(R.string.Are_connected_to_each_other);
            callStateTextView.setText(st1);
            handler.postDelayed(new Runnable() {
                public void run() {
                    streamID = playMakeCallSounds();
                }
            }, 300);
            try {
                // 拨打语音电话
                EMChatManager.getInstance().makeVideoCall(username);
            } catch (EMServiceNotReadyException e) {
                e.printStackTrace();
                final String st2 = getResources().getString(
                        R.string.Is_not_yet_connected_to_the_server);
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(RandomCallActivity.this, st2, 0).show();
                    }
                });
            }
        } else { // 有电话进来
            // 这里直接接通
            try {
                isAnswered = true;
                EMChatManager.getInstance().answerCall();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                // saveCallRecord(1);
                finish();
            }

        }

        countdownTimer.initTime(countdownTime);
        countdownTimer.setOnTimeCompleteListener(new OnTimeCompleteListener() {

            @Override
            public void onTimeComplete() {

                if (isBeLiked == false) {
                    // 三分钟未被喜欢直接关掉电话
                    if (soundPool != null)
                        soundPool.stop(streamID);
                    endCallTriggerByMe = true;
                    try {
                        EMChatManager.getInstance().endCall();
                    } catch (Exception e) {
                        e.printStackTrace();
                        finish();
                    }
                }
            }
        });
        // 设置监听
        if (charge != 0) {
            chronometer
                    .setOnChronometerTickListener(new OnChronometerTickListener() {

                        @Override
                        public void onChronometerTick(Chronometer chronometer) {

                        }
                    });
        }
    }

    public String getToUserId() {
        return username;
    }

    /**
     * 设置电话监听
     */
    void addCallStateListener() {
        callStateListener = new EMCallStateChangeListener() {

            @Override
            public void onCallStateChanged(CallState callState, CallError error) {
                // Message msg = handler.obtainMessage();
                switch (callState) {

                    case CONNECTING: // 正在连接对方
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                callStateTextView.setText(st1);
                            }

                        });
                        break;
                    case CONNECTED: // 双方已经建立连接
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                String st3 = getResources().getString(
                                        R.string.have_connected_with);
                                callStateTextView.setText(st3);

                            }

                        });
                        break;

                    case ACCEPTED: // 电话接通成功
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    if (soundPool != null)
                                        soundPool.stop(streamID);
                                } catch (Exception e) {
                                }
                                closeSpeakerOn();
                                chronometer.setVisibility(View.VISIBLE);
                                chronometer.setBase(SystemClock.elapsedRealtime());
                                // 修改自身状态
                                MLLovers lover = RandomCallMatchingActivity
                                        .getCurLover();
                                lover.setStatus(C.CALL_STATUS_CALLING);
                                lover.saveInBackground();
                                // 开始记时
                                chronometer.start();
                                String str4 = getResources().getString(
                                        R.string.In_the_call);
                                callStateTextView.setText(str4);
                                callingState = CallingState.NORMAL;
                                tvWaiting.setVisibility(View.GONE);
                                // 启动倒计时
                                countdownTimer.start();
                            }

                        });
                        break;
                    case DISCONNNECTED: // 电话断了
                        final CallError fError = error;
                        runOnUiThread(new Runnable() {
                            private void postDelayedCloseMsg() {
                                handler.postDelayed(new Runnable() {

                                    @Override
                                    public void run() {
                                        // saveCallRecord(1);
                                        Animation animation = new AlphaAnimation(
                                                1.0f, 0.0f);
                                        animation.setDuration(800);
                                        findViewById(R.id.root_layout)
                                                .startAnimation(animation);
                                        finish();
                                    }

                                }, 200);
                            }

                            @Override
                            public void run() {
                                chronometer.stop();
                                callDruationText = chronometer.getText().toString();
                                String st2 = getResources().getString(
                                        R.string.The_other_party_refused_to_accept);
                                String st3 = getResources().getString(
                                        R.string.Connection_failure);
                                String st4 = getResources().getString(
                                        R.string.The_other_party_is_not_online);
                                String st5 = getResources().getString(
                                        R.string.The_other_is_on_the_phone_please);

                                String st6 = getResources()
                                        .getString(
                                                R.string.The_other_party_did_not_answer_new);
                                String st7 = getResources().getString(
                                        R.string.hang_up);
                                String st8 = getResources().getString(
                                        R.string.The_other_is_hang_up);

                                String st9 = getResources().getString(
                                        R.string.did_not_answer);
                                String st10 = getResources().getString(
                                        R.string.Has_been_cancelled);
                                String st11 = getResources().getString(
                                        R.string.hang_up);

                                // 当电话断了可能对方异常退出
                                if (fError == CallError.REJECTED
                                        || fError == CallError.ERROR_INAVAILABLE
                                        || fError == CallError.ERROR_NORESPONSE) {
                                    MLUser user = new MLUser();
                                    user.setObjectId(username);
                                    AVQuery<MLLovers> query = new AVQuery<MLLovers>(
                                            "MLLovers");
                                    query.whereEqualTo("user", user);
                                    query.findInBackground(new FindCallback<MLLovers>() {

                                        @Override
                                        public void done(List<MLLovers> lovers,
                                                         AVException e) {
                                            if (e == null) {
                                                if (lovers.size() != 0) {
                                                    AVObject.deleteAllInBackground(
                                                            lovers, null);

                                                }
                                            }
                                        }
                                    });
                                }

                                if (fError == CallError.REJECTED) {
                                    callingState = CallingState.BEREFUESD;
                                    callStateTextView.setText(st2);
                                } else if (fError == CallError.ERROR_TRANSPORT) {
                                    callStateTextView.setText(st3);
                                } else if (fError == CallError.ERROR_INAVAILABLE) {
                                    callingState = CallingState.OFFLINE;
                                    callStateTextView.setText(st4);
                                } else if (fError == CallError.ERROR_BUSY) {
                                    callingState = CallingState.BUSY;
                                    callStateTextView.setText(st5);
                                } else if (fError == CallError.ERROR_NORESPONSE) {
                                    callingState = CallingState.NORESPONSE;
                                    callStateTextView.setText(st6);
                                } else {
                                    if (isAnswered) {
                                        callingState = CallingState.NORMAL;
                                        if (endCallTriggerByMe) {
                                            callStateTextView.setText(st7);
                                        } else {
                                            callStateTextView.setText(st8);
                                        }
                                    } else {
                                        if (isInComingCall) {
                                            callingState = CallingState.UNANSWERED;
                                            callStateTextView.setText(st9);
                                        } else {
                                            if (callingState != CallingState.NORMAL) {
                                                callingState = CallingState.CANCED;
                                                callStateTextView.setText(st10);
                                            } else {
                                                callStateTextView.setText(st11);
                                            }
                                        }
                                    }
                                }
                                postDelayedCloseMsg();
                            }

                        });

                        break;

                    default:
                        break;
                }

            }
        };
        EMChatManager.getInstance().addVoiceCallStateChangeListener(
                callStateListener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_refuse_call: // 拒绝接听
                if (ringtone != null)
                    ringtone.stop();
                try {
                    EMChatManager.getInstance().rejectCall();
                } catch (Exception e1) {
                    e1.printStackTrace();
                    // saveCallRecord(1);
                    finish();
                }
                callingState = CallingState.REFUESD;
                break;

            case R.id.ivChange: // 换人
                if (soundPool != null)
                    soundPool.stop(streamID);
                endCallTriggerByMe = true;
                try {
                    EMChatManager.getInstance().endCall();
                } catch (Exception e) {
                    e.printStackTrace();
                    // saveCallRecord(1);
                    finish();
                }
                break;

            case R.id.btn_hangup_call: // 挂断电话
                if (soundPool != null)
                    soundPool.stop(streamID);
                endCallTriggerByMe = true;
                try {
                    EMChatManager.getInstance().endCall();
                } catch (Exception e) {
                    e.printStackTrace();
                    // saveCallRecord(1);
                    finish();
                }
                break;

            case R.id.ivLike: // 喜欢
                if (liked == true) {
                    return;
                }
                ivLike.setImageResource(R.drawable.icon_call_liked);
                liked = true;
                refeshHeader(1);
                // 发一条透传过去告知对方自己已喜欢；
                EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                CmdMessageBody cmdBody = new CmdMessageBody(C.ACTION_CALL_LIKE);
                cmdMsg.setReceipt(username);
                cmdMsg.addBody(cmdBody);
                EMChatManager.getInstance().sendMessage(cmdMsg, null);
                break;
            case R.id.iv_handsfree: // 免提开关
                if (isHandsfreeState) {
                    // 关闭免提
                    handsFreeImage.setImageResource(R.drawable.icon_speaker_normal);
                    closeSpeakerOn();
                    isHandsfreeState = false;
                } else {
                    handsFreeImage.setImageResource(R.drawable.icon_speaker_on);
                    openSpeakerOn();
                    isHandsfreeState = true;
                }
                break;
            case R.id.ibClose:// 关闭页面
                final MyAlertDialog dialog = new MyAlertDialog(
                        RandomCallActivity.this).builder().setTitle("温馨提示")
                        .setMsg("您正在通话中是否挂断？")
                        .setNegativeButton("取消", new OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        });
                dialog.setPositiveButton("确定", new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (soundPool != null)
                            soundPool.stop(streamID);
                        endCallTriggerByMe = true;
                        try {
                            EMChatManager.getInstance().endCall();
                        } catch (Exception e) {
                            e.printStackTrace();
                            // saveCallRecord(1);
                            finish();
                        }
                    }
                });
                dialog.show();

                break;
            case R.id.tvReport:// 举报
                new ActionSheetDialog(RandomCallActivity.this)
                        .builder()
                        .setTitle("举报类型")
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("色情狂 ", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("色情狂 ");
                                    }
                                })
                        .addSheetItem("乱骂人", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("乱骂人");
                                    }
                                })
                        .addSheetItem("神经病", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("神经病");
                                    }
                                }).show();

                break;
            default:
                break;
        }
    }

    private void complain(final String type) {
        AVQuery<MLReportRecord> query = new AVQuery<MLReportRecord>(
                "MLReportRecord");
        final MLUser mlUser = new MLUser();
        mlUser.setObjectId(username);
        query.whereEqualTo("reportee", mlUser);
        query.whereEqualTo("reporter", UserService.getCurrentUser());
        query.findInBackground(new FindCallback<MLReportRecord>() {

            @Override
            public void done(List<MLReportRecord> mlReportRecords, AVException e) {
                if (e == null) {
                    if (mlReportRecords.size() > 0) { // 若本用户以前举报过
                        mlReportRecord = mlReportRecords.get(0);
                    } else { // 没举报过
                        mlReportRecord = new MLReportRecord();
                    }
                    mlReportRecord.setRemark(type);
                    mlReportRecord.setReporter(UserService.getCurrentUser());
                    mlReportRecord.setReportee(mlUser);
                    mlReportRecord.setStatus(C.REPORT_RECORD);
                    mlReportRecord.saveInBackground(new SaveCallback() {

                        @Override
                        public void done(AVException arg0) {
                            // method stub
                            if (arg0 == null) {
                                Map<String, Object> params = new HashMap<String, Object>();
                                final String userId = mlUser.getObjectId();
                                params.put("userId", userId);
                                AVCloud.callFunctionInBackground("reportUser",
                                        params, new FunctionCallback<Object>() {

                                            @Override
                                            public void done(Object arg0,
                                                             AVException e) {
                                                if (e == null) {
                                                    ToolKits.toast(
                                                            RandomCallActivity.this,
                                                            "举报成功");
                                                    AVAnalytics
                                                            .onEvent(
                                                                    RandomCallActivity.this,
                                                                    "举报");

                                                } else {
                                                    ToolKits.toast(
                                                            RandomCallActivity.this,
                                                            "网络错误，请稍后重试");
                                                }
                                            }
                                        });
                            } else {
                                ToolKits.toast(RandomCallActivity.this,
                                        "网络错误，请稍后重试");
                            }
                        }
                    });
                } else {
                    ToolKits.toast(RandomCallActivity.this, "网络错误，请稍后重试");
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        // 修改自身状态
        MLLovers lover = RandomCallMatchingActivity.getCurLover();
        lover.setStatus(C.CALL_STATUS_WAITING);
        lover.saveInBackground();
        super.onDestroy();
    }

    public void refeshHeader(int num) {
        if (liked == true && isBeLiked == true) {
            llCountDown.setVisibility(View.GONE);
            llHeaderContent.setVisibility(View.VISIBLE);
            llUserTip.setAnimation(null);
            llUserTip.setVisibility(View.GONE);
            rotate();
            topLayout.setVisibility(View.VISIBLE);
            countdownTimer.stop();
            if (num == 1) {
                EMConversation conversation = EMChatManager.getInstance()
                        .getConversation(UserService.getCurrentUserId());
                EMMessage message = EMMessage
                        .createSendMessage(EMMessage.Type.TXT);
                String content = "和你聊的很开心哦";
                TextMessageBody txtBody = new TextMessageBody(content);
                message.addBody(txtBody);

                // 增加自己特定的属性,消息类型
                // message.setAttribute(
                // "type",
                // C.EMMESSAGE_EXT_TYPE_CHAT_NOTIFICATION_MSG);

                message.setReceipt(username);
                conversation.addMessage(message);
                // 发送消息
                EMChatManager.getInstance().sendMessage(message, null);
            }
        }
    }

    private void rotate() {
        // float centerX = swing_card.getWidth() / 2f;
        // float centerY = swing_card.getHeight() / 2f;
        // // 构建3D旋转动画对象,旋转角度为0到90度 
        // Rotate3dAnimation rotation = new Rotate3dAnimation(0, 720, centerX,
        // centerY, 310.0f, true);
        // // 动画持续时间500毫秒 
        // rotation.setDuration(500);
        // // 动画完成后保持完成状态
        // rotation.setFillAfter(true);
        // rotation.setInterpolator(new AccelerateInterpolator());
        Rotate3dAnimation rotation = new Rotate3dAnimation(0, 0, 0, 0, 0, true);

        rotation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                // TODO Auto-generated method stub
                // swing_card.setAlpha(122);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // 获取布局的中心点位置，作为旋转的中心点
                float centerX = swing_card.getWidth() / 2f;
                float centerY = swing_card.getHeight() / 2f;

                // 构建3D旋转动画对象,旋转角度为90到0度
                Rotate3dAnimation rotation = new Rotate3dAnimation(720, 0,
                        centerX, centerY, 310.0f, false);
                // 动画持续时间500毫秒
                rotation.setDuration(1000);
                // 动画完成后保持完成状态
                rotation.setFillAfter(true);
                rotation.setInterpolator(new AccelerateInterpolator());
                swing_card.startAnimation(rotation);
            }
        });
        swing_card.startAnimation(rotation);

    }

    @Override
    public void onBackPressed() {

        final MyAlertDialog dialog = new MyAlertDialog(RandomCallActivity.this)
                .builder().setTitle("温馨提示").setMsg("您正在通话中是否挂断？")
                .setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(View v) {
                EMChatManager.getInstance().endCall();
                callDruationText = chronometer.getText().toString();
                // saveCallRecord(1);
                finish();
            }
        });
        dialog.show();

    }

}
